package com.zhongxi.guoyuan.wxapi;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMMin;
import com.zhongxi.guoyuan.OffLineShop.ConnectNet.NetWork;
import com.zhongxi.guoyuan.OffLineShop.Model.ItemShopInfo;
import com.zhongxi.guoyuan.OffLineShop.Model.SuccessPay;
import com.zhongxi.guoyuan.OffLineShop.UrlOffLine.RelativeUrl;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.EventBusMessage;
import com.zhongxi.guoyuan.entity.gift.GiftActivity;
import com.zhongxi.guoyuan.entity.gift.PayGiftSuccess;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.CommonTool;
import com.zhongxi.guoyuan.utils.Constants;
import com.zhongxi.guoyuan.utils.DataUtil;
import com.zhongxi.guoyuan.utils.GlideCircleTransform;
import com.zhongxi.guoyuan.utils.SpUtils;
import com.zhongxi.guoyuan.utils.ToastUtil;
import com.zhongxi.guoyuan.utils.UiUtils;
import com.zhongxi.guoyuan.view.ConsumerLoveYieldActivity;
import com.zhongxi.guoyuan.view.MainActivity;
import com.zhongxi.guoyuan.view.MainHomeActivity;
import com.zhongxi.guoyuan.view.PaySuccessActivity;
import com.zhongxi.guoyuan.view.user.MyDividendActivity;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.ResponseBody;
import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.GifImageView;


public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler, View.OnClickListener {


    TextView mTvStoreName;

    TextView mTvDiscount;

    TextView mTvShouldPrice;

    TextView mTvTruePrice;

    TextView mTvHongdou;

    TextView mTvMeidou;

    LinearLayout mLlContent;

    GifImageView mIvGif;

    TextView mTvGoHome;

    TextView mTvGoHd;

    TextView mTvComplain;


    TextView mTvGroup;

    ImageView mIvHead;

    ImageView mIvGroup1;

    ImageView mIvGroup2;


    TextView mTvOverTime;

    TextView mTvOverDay;

    TextView mTvRewardHd;

    TextView mTvRewardMd;

    TextView mTvRewardPoint;

    LinearLayout mLlTwoFlag;

    LinearLayout mLlThreeFlag;

    TextView mTvTwoHd;

    TextView mTvTwoFlag;

    TextView mTvThreeHd;

    TextView mTvThreeFlag;

    ImageView mImageView;

    TextView mTvShopName;

    TextView mTvAttr;

    TextView mTvGroupMoney;

    TextView mTvGroupNum;

    TextView mTvName;

    TextView mTvPhone;

    TextView mTvAddress;

    RelativeLayout mRlContent;

    private IWXAPI api;
    private TextView tvTitle;
    private ImageView ivBack;
    private DialogInterface.OnKeyListener keyListener = new DialogInterface.OnKeyListener() {
        @Override
        public boolean onKey(DialogInterface dialogInterface, int keyCode, KeyEvent keyEvent) {
            if (keyCode == KeyEvent.KEYCODE_BACK && keyEvent.getRepeatCount() == 0) {
                Intent intent = new Intent(WXPayEntryActivity.this, MainHomeActivity.class);
                startActivity(intent);
                finish();
                return true;
            }
            return false;
        }
    };
    private ProgressDialog mDialog;
    private ItemShopInfo mStore;
    private int mFlag = 0;
    List<String> otherIcon = new ArrayList<>();
    private String mShareKey;
    private JSONObject mActivity;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if ("gift".equals(MyApplication.getInstance().getPay())) {
            setContentView(R.layout.pay_result_gift);
            tvTitle = (TextView) findViewById(R.id.tvTitle);
            mIvHead = (ImageView) findViewById(R.id.iv_head);
            mIvGroup1 = (ImageView) findViewById(R.id.iv_group1);
            mIvGroup2 = (ImageView) findViewById(R.id.iv_group2);
            mTvOverTime = (TextView) findViewById(R.id.tv_overTime);
            mTvOverDay = (TextView) findViewById(R.id.tv_overDay);
            mTvRewardHd = (TextView) findViewById(R.id.tv_reward_hd);
            mTvRewardMd = (TextView) findViewById(R.id.tv_reward_md);
            mTvRewardPoint = (TextView) findViewById(R.id.tv_reward_point);
            mTvTwoHd = (TextView) findViewById(R.id.tv_two_hd);
            mTvTwoFlag = (TextView) findViewById(R.id.tv_two_flag);

            mLlTwoFlag = (LinearLayout) findViewById(R.id.ll_twoflag);
            mTvThreeHd = (TextView) findViewById(R.id.tv_three_hd);
            mTvThreeFlag = (TextView) findViewById(R.id.tv_three_flag);

            mLlThreeFlag = (LinearLayout) findViewById(R.id.ll_threeflag);
            mTvGoHome = (TextView) findViewById(R.id.tv_goHome);
            mTvGroup = (TextView) findViewById(R.id.tv_group);
            mImageView = (ImageView) findViewById(R.id.imageView);
            mTvShopName = (TextView) findViewById(R.id.tv_shop_name);
            mTvAttr = (TextView) findViewById(R.id.tv_attr);
            mTvGroupMoney = (TextView) findViewById(R.id.tv_group_money);
            mTvGroupNum = (TextView) findViewById(R.id.tv_groupNum);
            mTvName = (TextView) findViewById(R.id.tv_name);
            mTvPhone = (TextView) findViewById(R.id.tv_phone);
            mTvAddress = (TextView) findViewById(R.id.tv_address);
            mRlContent = (RelativeLayout) findViewById(R.id.Rl_content);
            if (SpUtils.getInstance().readIntSp("userType") == 2) {
                tvTitle.setText("一键开团成功");
                mLlTwoFlag.setVisibility(View.VISIBLE);
                mLlThreeFlag.setVisibility(View.VISIBLE);
                mTvGoHome.setVisibility(View.GONE);
                mTvGroup.setText("邀友参团");
            } else {
                tvTitle.setText("我要参团");
                mLlTwoFlag.setVisibility(View.GONE);
                mLlThreeFlag.setVisibility(View.GONE);
                mTvGoHome.setVisibility(View.VISIBLE);
                mTvGroup.setText("团购秒杀");
            }
        } else {
            setContentView(R.layout.pay_result);
            tvTitle = (TextView) findViewById(R.id.tvTitle);
            mTvStoreName = (TextView) findViewById(R.id.tv_storeName);
            mTvDiscount = (TextView) findViewById(R.id.tv_discount);
            mTvShouldPrice = (TextView) findViewById(R.id.tv_shouldPrice);
            mTvTruePrice = (TextView) findViewById(R.id.tv_truePrice);
            mTvHongdou = (TextView) findViewById(R.id.tv_hongdou);
            mTvMeidou = (TextView) findViewById(R.id.tv_meidou);
            mTvGoHome = (TextView) findViewById(R.id.tv_goHome);

            mIvGif = (GifImageView) findViewById(R.id.iv_gif);
            mTvGoHd = (TextView) findViewById(R.id.tv_goHd);
            mTvComplain = (TextView) findViewById(R.id.tv_complain);
            mLlContent = (LinearLayout) findViewById(R.id.ll_content);
            tvTitle.setText("支付成功");
            try {
                GifDrawable mGifDrawable = new GifDrawable(getResources(), R.drawable.celebrate);
                mGifDrawable.setLoopCount(1000);
                mIvGif.setImageDrawable(mGifDrawable);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        ivBack = (ImageView) findViewById(R.id.ivBack);
        api = WXAPIFactory.createWXAPI(this, Constants.APP_ID);
        api.handleIntent(getIntent(), this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }

    @Override
    public void onReq(BaseReq req) {
    }

    @Override
    public void onResp(BaseResp resp) {
        int code = resp.errCode;
        if (code == -2) {
            if (null != MyApplication.getInstance().getPay() && !"".equals(MyApplication.getInstance().getPay())) {
                if ("gift".equals(MyApplication.getInstance().getPay())) {
                    if (SpUtils.getInstance().readIntSp("userType") == 2) {
                        tvTitle.setText("开团失败");
                    } else {
                        tvTitle.setText("参团失败");
                    }
                    getGiftFail();
                } else {
                    tvTitle.setText("支付失败");  //支付取消
                    if ("facetoface".equals(MyApplication.getInstance().getPay())) {
                        getFaceToFaceFailing();
                        showFaceWindow();
                    } else if ("upface".equals(MyApplication.getInstance().getPay())
                            || "offline".equals(MyApplication.getInstance().getPay())) {
                        showFailFacePw();
                    } else if ("exchange".equals(MyApplication.getInstance().getPay())) {
                        showExchangeResultDialog(0);
                    } else {
                        SpUtils.getInstance().saveSp("rewardPrice", "");
                        showFailPopWindow();
                    }
                }
            }
        } else if (code == -1) {   //支付失败
            if (null != MyApplication.getInstance().getPay() && !"".equals(MyApplication.getInstance().getPay())) {
                if ("gift".equals(MyApplication.getInstance().getPay())) {
                    if (SpUtils.getInstance().readIntSp("userType") == 2) {
                        tvTitle.setText("开团失败");
                    } else {
                        tvTitle.setText("参团失败");
                    }
                    getGiftFail();
                } else {
                    tvTitle.setText("支付失败");
                    if ("facetoface".equals(MyApplication.getInstance().getPay())) {    //当面付
                        getFaceToFaceFailing();
                        showFaceWindow();
                    } else if ("upface".equals(MyApplication.getInstance().getPay())
                            || "offline".equals(MyApplication.getInstance().getPay())) {
                        showFailFacePw();
                    } else if ("exchange".equals(MyApplication.getInstance().getPay())) {
                        showExchangeResultDialog(0);
                    } else {
                        SpUtils.getInstance().saveSp("rewardPrice", "");
                        showFailPopWindow();
                    }
                }
            }
        } else {
            if (null != MyApplication.getInstance().getPay() && !"".equals(MyApplication.getInstance().getPay())) {
                if (MyApplication.getInstance().getPay().equals("beauty")) {
                    showPopupWindow();
                } else if ("facetoface".equals(MyApplication.getInstance().getPay())) {
                    MyApplication.getInstance().sharedPrefrences.edit().putString("orderId", "").commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("certificate", "").commit();
                    showRewardWindow();
                } else if ("offline".equals(MyApplication.getInstance().getPay())) {
                    mLlContent.setVisibility(View.VISIBLE);
                    if (mDialog == null) {
                        mDialog = ProgressDialog.show(WXPayEntryActivity.this, "提示", "正在加载中...");
                    }
                    paySuccess();
                } else if ("exchange".equals(MyApplication.getInstance().getPay())) {
                    showAlipaySuccessResult(MyApplication.getInstance().getPayRedBean());
                } else if ("gift".equals(MyApplication.getInstance().getPay())) {
                    mRlContent.setVisibility(View.VISIBLE);
                    payGiftSuccess();
                } else {   //if (MyApplication.getInstance().getPay().equals("reward"))
                    showRewardWindow();  //  线上超市
                }
            }
        }
    }

    private void getGiftFail() {
        unsubscribe();
        NetWork.getOffLineApi().getGiftPayFailApi(RelativeUrl.GIFTPAYFAILURE + MyApplication.getInstance().getUrl(),
                MyApplication.getInstance().getCheck(false), SpUtils.getInstance().readSp("orderid"),
                SpUtils.getInstance().readSp("vc"), SpUtils.getInstance().readSp("cert"))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<BaseResponse>() {
                    @Override
                    public void accept(BaseResponse baseResponse) throws Exception {
                        MyApplication.getInstance().setSpValue(baseResponse.getSafeobj());
                        showFailFacePw();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        ToastUtil.show(getString(R.string.load_error));
                        finish();
                        startActivity(new Intent(UiUtils.getContext(), MainHomeActivity.class));
                    }
                });
    }

    private void payGiftSuccess() {
        unsubscribe();
        NetWork.getOffLineApi().getGiftPaySuccessApi(RelativeUrl.GIFTPAYSUCCESS + MyApplication.getInstance().getUrl(),
                MyApplication.getInstance().getCheck(false), SpUtils.getInstance().readSp("orderid"),
                SpUtils.getInstance().readSp("vc"), SpUtils.getInstance().readSp("cert"))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<ResponseBody>() {
                    @Override
                    public void accept(ResponseBody responseBody) throws Exception {
                        JSONObject jsonObject = new JSONObject(responseBody.string());
                        JSONObject safeobj = jsonObject.optJSONObject("safeobj");
                        MyApplication.getInstance().sharedPrefrences.edit().putString("now", safeobj.optString("now")).commit();
                        MyApplication.getInstance().sharedPrefrences.edit().putString("sk", safeobj.optString("safestring")).commit();
                        int mCode = jsonObject.optInt("code");
                        if (mCode == 1) {
                            mActivity = jsonObject.optJSONObject("activity");
                            mShareKey = jsonObject.optString("shareKey");
                            if (mActivity != null && mActivity.length() > 0) {
                                mTvOverTime.setText("活动截止:" + mActivity.optString("etime"));
                                if (CommonTool.TimeCompareTime(mActivity.optString("stime"), mActivity.optString("etime")) > 0) {
                                    mTvOverDay.setText("还剩 " + CommonTool.TimeCompareTime(mActivity.optString("stime"), mActivity.optString("etime")) + " 天");
                                } else {
                                    mTvOverDay.setText("该活动结束");
                                }
                                if (!TextUtils.isEmpty(mActivity.optString("redbeanfparticipants"))) {
                                    mTvRewardHd.setVisibility(View.VISIBLE);
                                    mTvRewardHd.setText("奖励 " + mActivity.optString("redbeanfparticipants") + " 红豆");
                                } else {
                                    mTvRewardHd.setVisibility(View.GONE);
                                }
                                if (!TextUtils.isEmpty(mActivity.optString("innerfparticipants"))) {
                                    mTvRewardMd.setVisibility(View.VISIBLE);
                                    mTvRewardMd.setText("奖励 " + mActivity.optString("innerfparticipants") + " 美豆");
                                } else {
                                    mTvRewardMd.setVisibility(View.GONE);
                                }
                                if (!TextUtils.isEmpty(mActivity.optString("cpfparticipants"))) {
                                    mTvRewardPoint.setVisibility(View.VISIBLE);
                                    mTvRewardPoint.setText("奖励 " + mActivity.optString("cpfparticipants") + " 点合伙人分润权");
                                } else {
                                    mTvRewardPoint.setVisibility(View.GONE);
                                }
                                if (!TextUtils.isEmpty(mActivity.optString("twogroupback"))) {
                                    mTvTwoHd.setText(mActivity.optString("twogroupback") + " 元");
                                } else {
                                    mTvTwoFlag.setVisibility(View.GONE);
                                }
                                if (!TextUtils.isEmpty(mActivity.optString("threegroupback"))) {
                                    mTvThreeHd.setText(mActivity.optString("threegroupback") + " 元");
                                } else {
                                    mTvThreeFlag.setVisibility(View.GONE);
                                }

                                String mS = mActivity.optString("gattr");
                                if (!TextUtils.isEmpty(mS)) {
                                    JSONObject mGattr = new JSONObject(mS);
                                    Iterator<String> keys = mGattr.keys();
                                    String attr = "";
                                    while (keys.hasNext()) {
                                        String next = keys.next();
                                        String attrValue = mGattr.optString(next);
                                        attr += attrValue + "/";
                                    }
                                    mTvAttr.setText("规格: " + attr.substring(0, attr.length() - 1));
                                } else {
                                    mTvAttr.setText("");
                                }

                                mTvGroupMoney.setText("团购价: " + mActivity.optString("aprice") + " 元");
                                mTvGroupNum.setText("X " + SpUtils.getInstance().readIntSp("num"));
                            }
                            JSONObject mOrderCus = jsonObject.optJSONObject("orderCus");  // 邮寄
                            if (mOrderCus != null && mOrderCus.length() > 0) {
                                if (!TextUtils.isEmpty(mOrderCus.optString("consignee"))) {
                                    mTvName.setText(mOrderCus.optString("consignee"));
                                    mTvPhone.setText(mOrderCus.optString("consigneemphone"));
                                    mTvAddress.setText(mOrderCus.optString("shippingaddress"));
                                } else {
                                    JSONObject mStoreInfo = jsonObject.optJSONObject("storeInfo");
                                    if (mStoreInfo != null && mStoreInfo.length() > 0) {
                                        mTvName.setText(mStoreInfo.optString("name"));
                                        mTvPhone.setText(mStoreInfo.optString("mphone"));
                                        mTvAddress.setText(mStoreInfo.optString("address"));
                                    }
                                }
                            } else {
                                JSONObject mStoreInfo = jsonObject.optJSONObject("storeInfo");
                                if (mStoreInfo != null && mStoreInfo.length() > 0) {
                                    mTvName.setText(mStoreInfo.optString("name"));
                                    mTvPhone.setText(mStoreInfo.optString("mphone"));
                                    mTvAddress.setText(mStoreInfo.optString("address"));
                                }
                            }

                            JSONObject mRefInfo = jsonObject.optJSONObject("refInfo");
                            if (mRefInfo != null && mRefInfo.length() > 0) {
                                Glide.with(UiUtils.getContext()).load(Url.IMG_URL + mRefInfo.optString("images"))
                                        .placeholder(R.mipmap.iv_loading).into(mImageView);
                                mTvShopName.setText(mRefInfo.optString("name"));

                            }

                            JSONObject mGroupInfo = jsonObject.optJSONObject("groupInfo");
                            if (mGroupInfo != null && mGroupInfo.length() > 0) {
                                if (!TextUtils.isEmpty(mGroupInfo.optString("twogroupisback"))) {
                                    mTvTwoFlag.setVisibility(View.VISIBLE);
                                    mTvThreeFlag.setVisibility(View.VISIBLE);
                                    if ("1".equals(mGroupInfo.optString("twogroupisback"))) {
                                        mTvTwoFlag.setText("(已返还)");
                                    } else {
                                        mTvTwoFlag.setText("(未返还)");
                                    }
                                    if ("1".equals(mGroupInfo.optString("threegroupisback"))) {
                                        mTvThreeFlag.setText("(已返还)");
                                    } else {
                                        mTvThreeFlag.setText("(未返还)");
                                    }
                                } else {
                                    mTvTwoFlag.setVisibility(View.GONE);
                                    mTvThreeFlag.setVisibility(View.GONE);
                                }
                                if (!TextUtils.isEmpty(mGroupInfo.optString("userid"))) {
                                    JSONObject mParticipants = jsonObject.optJSONObject("participants");
                                    if (mParticipants != null && mParticipants.length() > 0) {
//                                        Glide.with(UiUtils.getContext())
//                                                .load(Url.BASE_URL + mParticipants.optString(mGroupInfo.optString("userid")))
//                                                .placeholder(R.mipmap.iv_avatar).transform(new GlideCircleTransform(UiUtils.getContext()))
//                                                .into(mIvHead);
                                        Iterator<String> mKeys = mParticipants.keys();
                                        while (mKeys.hasNext()) {
                                            String mNext = mKeys.next();
                                            String value = mParticipants.optString(mNext);
                                            if (mNext.equals(mGroupInfo.optString("userid"))) {
                                                setIcon(value, mIvHead);
                                            } else {
                                                otherIcon.add(value);
                                            }
                                        }

                                        if (otherIcon.size() == 1) {
                                            setIcon(otherIcon.get(0), mIvGroup1);
                                        } else if (otherIcon.size() == 2) {
                                            setIcon(otherIcon.get(0), mIvGroup1);
                                            setIcon(otherIcon.get(1), mIvGroup2);
                                        }
                                    }
                                }
                            } else {
                                mTvTwoFlag.setVisibility(View.GONE);
                                mTvThreeFlag.setVisibility(View.GONE);
                            }
                        } else {
                            ToastUtil.show(getString(R.string.loseData, mCode));
                            finish();
                            startActivity(new Intent(UiUtils.getContext(), MainHomeActivity.class));
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        ToastUtil.show(getString(R.string.load_error));
                        finish();
                        startActivity(new Intent(UiUtils.getContext(), MainHomeActivity.class));
                    }
                });
    }

    private void setIcon(String value, ImageView imageView) {
        if (value.startsWith("http://") || value.startsWith("https://")) {
            Glide.with(UiUtils.getContext())
                    .load(value)
                    .placeholder(R.mipmap.iv_avatar).transform(new GlideCircleTransform(UiUtils.getContext()))
                    .into(imageView);
        } else {
            Glide.with(UiUtils.getContext())
                    .load(Url.BASE_URL + value)
                    .placeholder(R.mipmap.iv_avatar).transform(new GlideCircleTransform(UiUtils.getContext()))
                    .into(imageView);
        }
    }

    int count = 1;

    private void paySuccess() {
        unsubscribe();
        NetWork.getOffLineApi().paySuccessApi(RelativeUrl.PAYSUCCESS + MyApplication.getInstance().getUrl(),
                MyApplication.getInstance().getCheck(false), SpUtils.getInstance().readSp("orderid"), SpUtils.getInstance().readSp("checksum"))
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<SuccessPay>() {
                    @Override
                    public void accept(SuccessPay successPay) throws Exception {
                        MyApplication.getInstance().setSpValue(successPay.safeobj);
                        if (successPay.code == 1) {
                            if (mDialog != null) {
                                mDialog.dismiss();
                            }
                            if (successPay.store != null && !"".equals(successPay.store)) {
                                mStore = successPay.store;
                                mTvStoreName.setText("收款方: " + mStore.getName());
                            }
                            if (successPay.order != null && !"".equals(successPay.order)) {
                                SuccessPay.SuccessOrder mOrder = successPay.order;
                                if ("100".equals(mOrder.storediscount)) {
                                    mTvDiscount.setText("暂无折扣");
                                } else {
                                    mTvDiscount.setText(mOrder.storediscount + " 折结账");
                                }
                                mTvShouldPrice.setText("感谢消费 " + mOrder.shouldprice + " 元");
                                mTvTruePrice.setText("成功实付 " + mOrder.payprice + " 元");
                                mTvHongdou.setText("+" + mOrder.backcashnum + " 元");
                                mTvMeidou.setText("+" + mOrder.backinnernum + " 美豆");
                            }
                        } else if (successPay.code == 7003) {
                            count++;
                            if (count < 6) {
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            Thread.sleep(2500);
                                            new Handler().post(new Runnable() {
                                                @Override
                                                public void run() {
                                                    paySuccess();
                                                }
                                            });
                                        } catch (InterruptedException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }).start();
                            } else {
                                if (mDialog != null) {
                                    mDialog.dismiss();
                                }
                                ToastUtil.show("连接服务器失败");
                                finish();
                                startActivity(new Intent(UiUtils.getContext(), MainHomeActivity.class));
                            }
                        } else {
                            if (mDialog != null) {
                                mDialog.dismiss();
                            }
                            ToastUtil.show(getString(R.string.loseData, successPay.code));
                            finish();
                            startActivity(new Intent(UiUtils.getContext(), MainHomeActivity.class));
                        }

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        if (mDialog != null) {
                            mDialog.dismiss();
                        }
                        ToastUtil.show(getString(R.string.load_error));
                        finish();
                        startActivity(new Intent(UiUtils.getContext(), MainHomeActivity.class));
                    }
                });
    }

    /***
     * 豆豆兑换支付成功
     */
    private void showExchangeResultDialog(int i) {
        LayoutInflater inflater = LayoutInflater.from(this);
        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_pay_success, null);
        final AlertDialog dialog = new AlertDialog.Builder(WXPayEntryActivity.this).create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.setOnKeyListener(keyListener);
        dialog.show();
        dialog.getWindow().setContentView(layout);
        TextView tvContent = (TextView) layout.findViewById(R.id.tvContent);
        TextView tvDes = (TextView) layout.findViewById(R.id.tv_dec);
        TextView tvTitle = (TextView) layout.findViewById(R.id.tv_title);

        if (i == 0) {
            tvTitle.setText(getString(R.string.exchangeNoSuccessTip));
            tvDes.setText(getString(R.string.exchangeNoSuccessContent));
        }
        tvContent.setVisibility(View.GONE);
        ImageView iv_Cancel = (ImageView) layout.findViewById(R.id.iv_Cancel);
        iv_Cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                finish();
                Intent intent = new Intent(WXPayEntryActivity.this, MainHomeActivity.class);
                startActivity(intent);
            }
        });
        TextView btSure = (TextView) layout.findViewById(R.id.btSure);

        btSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                finish();
                Intent intent = new Intent(WXPayEntryActivity.this, MainHomeActivity.class);
                startActivity(intent);
            }
        });
    }

    private void showAlipaySuccessResult(String bean) {
        LayoutInflater inflater = LayoutInflater.from(this);
        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_exchange_paysuccess, null);
        final AlertDialog dialog = new AlertDialog.Builder(this).create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        dialog.getWindow().setContentView(layout);

        TextView tvContent2 = (TextView) layout.findViewById(R.id.tvContent2);
        tvContent2.setText("奖励您 " + bean + " 元");
        TextView tvSurePay = (TextView) layout.findViewById(R.id.tvSurePay);

        tvSurePay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                startActivity(new Intent(WXPayEntryActivity.this, MainHomeActivity.class));
            }
        });

    }

    /**
     * 线下超市商家
     */
    private void showPaySuccessDialogOffLine() {
        final android.app.AlertDialog mDialog = new android.app.AlertDialog.Builder(WXPayEntryActivity.this).create();
        View view = UiUtils.inflate(R.layout.dialog_pay_success_offline);
        ImageView mImageVie = (ImageView) view.findViewById(R.id.iv_cancel);
        final RatingBar mRatingBar = (RatingBar) view.findViewById(R.id.ratingBar);
        final EditText et_evaluate = (EditText) view.findViewById(R.id.et_evaluate);
        final TextView long_evaluate = (TextView) view.findViewById(R.id.long_evaluate);
        Button btn_reset = (Button) view.findViewById(R.id.btn_reset);
        Button btn_submit = (Button) view.findViewById(R.id.btn_submit);
        mImageVie.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mDialog.dismiss();
            }
        });
        btn_reset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mRatingBar.setRating(0);
                et_evaluate.setText("");
            }
        });
        btn_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String mTrim = et_evaluate.getText().toString().trim();
                if (!TextUtils.isEmpty(mTrim) && mRatingBar.getRating() != 0) {
                    mDialog.dismiss();
                    String rb = String.valueOf(mRatingBar.getRating());
                    addComment(mTrim, Integer.parseInt(rb.substring(0, rb.indexOf("."))));
                } else {
                    ToastUtil.show(getString(R.string.comment_nofinish));
                }
            }
        });
        et_evaluate.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                long_evaluate.setText("0/200");
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                long_evaluate.setText(s.length() + "/200");
            }
        });
        mDialog.setCanceledOnTouchOutside(false);
        mDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialogInterface, int i, KeyEvent keyEvent) {
                if (i == KeyEvent.KEYCODE_BACK && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
                    mDialog.dismiss();
                    finish();
                    startActivity(new Intent(UiUtils.getContext(), MainHomeActivity.class));
                    return true;
                }
                return false;
            }
        });
        mDialog.setView(view);
        mDialog.show();
    }

    private Disposable mDisposable;

    private void addComment(String trim, int rating) {
        unsubscribe();
        mDisposable = NetWork.getOffLineApi().addCommentApi(RelativeUrl.ADDCOMMENT + MyApplication.getInstance().getUrl(),
                MyApplication.getInstance().getCheck(false), mStore.getId(), SpUtils.getInstance().readSp("orderid"), rating, trim)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        if (mDialog == null) {
                            mDialog = ProgressDialog.show(WXPayEntryActivity.this, "提示", "正在加载中...");
                        }
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<BaseResponse>() {
                    @Override
                    public void accept(BaseResponse baseResponse) throws Exception {
                        if (mDialog != null && mDialog.isShowing()) {
                            mDialog.dismiss();
                        }
                        MyApplication.getInstance().setSpValue(baseResponse.getSafeobj());
                        if (baseResponse.getCode() != 1) {
                            ToastUtil.show(getString(R.string.losePay, baseResponse.getCode()));
                        } else {
                            mFlag = 1;
                            mTvComplain.setBackground(getResources().getDrawable(R.drawable.shape3));
                            mTvComplain.setTextColor(getResources().getColor(R.color.gohere));
                            mTvComplain.setText("已评论");
                            ToastUtil.show("评论成功");
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        if (mDialog != null && mDialog.isShowing()) {
                            mDialog.dismiss();
                        }
                        ToastUtil.show(getString(R.string.load_error));
                    }
                });
    }


    private void showFailFacePw() {
        LayoutInflater inflater = LayoutInflater.from(this);
        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_pay_fail, null);
        final AlertDialog dialog = new AlertDialog.Builder(this).create();
        dialog.setCanceledOnTouchOutside(false);
        Window window = dialog.getWindow();
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.show();
        dialog.getWindow().setContentView(layout);
        TextView tv_title = (TextView) layout.findViewById(R.id.tv_title);
        tv_title.setText("抱歉, 您支付未成功!");
        TextView tvContent = (TextView) layout.findViewById(R.id.tvContent);
        tvContent.setVisibility(View.GONE);
        ImageView iv_Cancel = (ImageView) layout.findViewById(R.id.iv_Cancel);
        dialog.setOnKeyListener(keyListener);
        iv_Cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                finish();
                Intent intent = new Intent(WXPayEntryActivity.this, MainHomeActivity.class);
                startActivity(intent);
            }
        });
        TextView btSure = (TextView) layout.findViewById(R.id.btSure);
        btSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                finish();
                Intent intent = new Intent(WXPayEntryActivity.this, MainHomeActivity.class);
                startActivity(intent);
            }
        });
    }

    private void getFaceToFaceFailing() {
        Map<String, String> map = new HashMap<>();
        map.put("orderid", MyApplication.getInstance().getQrPayFailOrderId());
        map.put("certificate", MyApplication.getInstance().getQrPayFailCertificate());
        String baseUrl = "/" + MyApplication.getInstance().getUrl() + "?params=" + MyApplication.getInstance().getCheck(false);
        OkHttpUtils.post()
                .url(Url.QRCODEFAILE + baseUrl)
                .params(map)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        System.out.println("on error 扫码支付失败::" + e.getMessage().toString());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        try {
                            Gson gson = new Gson();
                            BaseResponse baseResponse = gson.fromJson(response, BaseResponse.class);
                            MyApplication.getInstance().setSpValue(baseResponse.getSafeobj());
                            if (baseResponse.getCode() == 1000) {
                                ToastUtil.show("参数错误");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }


    private void showFaceWindow() {
        LayoutInflater inflater = LayoutInflater.from(this);
        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_pay_fail, null);
        final AlertDialog dialog = new AlertDialog.Builder(WXPayEntryActivity.this).create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.setOnKeyListener(keyListener);
        dialog.show();
        dialog.getWindow().setContentView(layout);
        TextView tvContent = (TextView) layout.findViewById(R.id.tvContent);
        tvContent.setVisibility(View.GONE);
        ImageView iv_Cancel = (ImageView) layout.findViewById(R.id.iv_Cancel);
        iv_Cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                Intent intent = new Intent(WXPayEntryActivity.this, MainHomeActivity.class);
                startActivity(intent);
                finish();
            }
        });
        TextView btSure = (TextView) layout.findViewById(R.id.btSure);
        btSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                Intent intent = new Intent(WXPayEntryActivity.this, MainHomeActivity.class);
                startActivity(intent);
                finish();
            }
        });
    }

    private void showShopWindow() {
        LayoutInflater inflater = LayoutInflater.from(this);
        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_pay_success, null);
        final AlertDialog dialog = new AlertDialog.Builder(this).create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        dialog.getWindow().setContentView(layout);
        dialog.setOnKeyListener(keyListener);
        ImageView iv_Cancel = (ImageView) layout.findViewById(R.id.iv_Cancel);
        iv_Cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                Intent intent = new Intent(WXPayEntryActivity.this, MainHomeActivity.class);
                startActivity(intent);
                finish();
            }
        });

        TextView tv_dec = (TextView) layout.findViewById(R.id.tv_dec);
        tv_dec.setText("本次消费您获得:");
        TextView tvContent = (TextView) layout.findViewById(R.id.tvContent);
        tvContent.setVisibility(View.VISIBLE);
        String mSubstring = DataUtil.formatData(MyApplication.getInstance().getWinXinMD()).substring(0, DataUtil.formatData(MyApplication.getInstance().getWinXinMD()).length() - 3);
        tvContent.setText(mSubstring + " 美豆");
        TextView btSure = (TextView) layout.findViewById(R.id.btSure);
        btSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                Intent intent = new Intent(WXPayEntryActivity.this, MainHomeActivity.class);
                startActivity(intent);
                finish();
            }
        });
    }

    /**
     * 返银商品支付成功
     */
    private void showRewardWindow() {
        final LayoutInflater inflater = LayoutInflater.from(this);
        final AlertDialog dialog = new AlertDialog.Builder(WXPayEntryActivity.this, R.style.Translucent_NoTitle).create();
        View mView = inflater.inflate(R.layout.dialog_pay_story_success, null);
        dialog.setView(mView);
        dialog.show();
        dialog.setCanceledOnTouchOutside(false);
        dialog.setOnKeyListener(keyListener);
        ImageView iv_Cancel = (ImageView) mView.findViewById(R.id.iv_Cancel);
        TextView tv_know = (TextView) mView.findViewById(R.id.tv_know);
        TextView tv_content = (TextView) mView.findViewById(R.id.tv_content);
        iv_Cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                Intent intent = new Intent(UiUtils.getContext(), MainHomeActivity.class);
                startActivity(intent);
                finish();
            }
        });
        tv_know.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                Intent intent = new Intent(UiUtils.getContext(), MainHomeActivity.class);
                startActivity(intent);
                finish();
            }
        });
        tv_content.setText("获赠 " + SpUtils.getInstance().readSp("rewardPrice") + " 美豆");
    }

    /**
     * 美币美容院支付成功
     */
    private void showPopupWindow() {
        LayoutInflater inflater = LayoutInflater.from(this);
        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_pay_success, null);
        final AlertDialog dialog = new AlertDialog.Builder(WXPayEntryActivity.this).create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.setOnKeyListener(keyListener);
        dialog.show();
        dialog.getWindow().setContentView(layout);
        ImageView iv_Cancel = (ImageView) layout.findViewById(R.id.iv_Cancel);
        iv_Cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                Intent intent = new Intent(WXPayEntryActivity.this, MainHomeActivity.class);
                startActivity(intent);
                finish();
            }
        });
        TextView tv_dec = (TextView) layout.findViewById(R.id.tv_dec);
        tv_dec.setText("我们的客服会及时跟您电话沟通，以确认到店护理时间，请留意手机接听！");
        TextView tvContent = (TextView) layout.findViewById(R.id.tvContent);
        tvContent.setVisibility(View.GONE);
        TextView btSure = (TextView) layout.findViewById(R.id.btSure);
        btSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                Intent intent = new Intent(WXPayEntryActivity.this, MainHomeActivity.class);
                startActivity(intent);
                finish();
            }
        });
    }


    private void showFailPopWindow() {
        LayoutInflater inflater = LayoutInflater.from(this);
        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_pay_fail, null);
        final AlertDialog dialog = new AlertDialog.Builder(WXPayEntryActivity.this).create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.setOnKeyListener(keyListener);
        dialog.show();
        dialog.getWindow().setContentView(layout);
        TextView tvContent = (TextView) layout.findViewById(R.id.tvContent);
        tvContent.setVisibility(View.VISIBLE);
        ImageView iv_Cancel = (ImageView) layout.findViewById(R.id.iv_Cancel);
        iv_Cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                Intent intent = new Intent(WXPayEntryActivity.this, MainHomeActivity.class);
                startActivity(intent);
                finish();
            }
        });
        TextView btSure = (TextView) layout.findViewById(R.id.btSure);
        btSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                Intent intent = new Intent(WXPayEntryActivity.this, MainHomeActivity.class);
                startActivity(intent);
                finish();
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            Intent intent = new Intent(WXPayEntryActivity.this, MainHomeActivity.class);
            startActivity(intent);
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unsubscribe();
    }

    protected void unsubscribe() {
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        ivBack.setOnClickListener(this);
        mTvGoHome.setOnClickListener(this);
        if ("gift".equals(MyApplication.getInstance().getPay())) {
            mTvGroup.setOnClickListener(this);
        } else {
            mTvGoHd.setOnClickListener(this);
            mTvComplain.setOnClickListener(this);
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
        startActivity(new Intent(this, MainHomeActivity.class));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivBack:
                finish();
                startActivity(new Intent(this, MainHomeActivity.class));
                break;
            case R.id.tv_goHome:
                finish();
                Intent mIntent = new Intent(this, MainActivity.class);
                mIntent.putExtra("index", 3);
                mIntent.putExtra("entorypay", "paysuccess");
                startActivity(mIntent);
                break;
            case R.id.tv_goHd:
                finish();
                Intent intentHd = new Intent(this, ConsumerLoveYieldActivity.class);
                intentHd.putExtra("entryto", 1);
                startActivity(intentHd);
                break;
            case R.id.tv_complain:
                if (mFlag != 1) {
                    showPaySuccessDialogOffLine();
                }
                break;
            case R.id.tv_group:
                if (SpUtils.getInstance().readIntSp("userType") == 2) {
                    if (!TextUtils.isEmpty(mShareKey)) {
                        UMMin umMin = new UMMin("gh_b944d829971d");
                        UMImage imagelocal = new UMImage(UiUtils.getContext(), R.mipmap.logo);
                        umMin.setThumb(imagelocal);
                        umMin.setTitle(mActivity.optString("name").trim());
                        umMin.setDescription(mActivity.optString("subject").trim());
                        umMin.setPath("/pages/seckilldtl/seckilldtl?id=" + mActivity.optString("id") + "&sharekey=" + mShareKey);
                        umMin.setUserName("gh_b944d829971d");  // 原始id  -->小程序提供
                        new ShareAction(this)
                                .withMedia(umMin)
                                .setPlatform(SHARE_MEDIA.WEIXIN)
                                .setCallback(new UMShareListener() {
                                    @Override
                                    public void onStart(SHARE_MEDIA share_media) {
                                    }

                                    @Override
                                    public void onResult(SHARE_MEDIA share_media) {
                                        ToastUtil.show("分享成功了");
                                        finish();
                                        startActivity(new Intent(UiUtils.getContext(), MainHomeActivity.class));
                                    }

                                    @Override
                                    public void onError(SHARE_MEDIA share_media, Throwable throwable) {
                                        finish();
                                        startActivity(new Intent(UiUtils.getContext(), MainHomeActivity.class));
                                    }

                                    @Override
                                    public void onCancel(SHARE_MEDIA share_media) {
                                        finish();
                                        startActivity(new Intent(UiUtils.getContext(), MainHomeActivity.class));
                                    }
                                }).share();
                    } else {
                        ToastUtil.show("暂无分享功能,敬请期待!");
                    }
                } else {// 团购秒杀
//                    Intent mIntent = new Intent(this, MainActivity.class);
//                    mIntent.putExtra("index", 4);
//                    startActivity(mIntent);
                }
                break;
        }
    }
}